<template>
	<globalModal
		:title="title"
		:visible="visible"
		:confirmLoading="confirmLoading"
		@ok="handleOk"
		@cancel="handleCancel"
	>
		<a-spin :spinning="confirmLoading">
			<a-form :form="form" autocomplete="off" :labelCol="labelCol" :wrapperCol="wrapperCol">
				<!-- <a-form-item label="账号类型" v-if="isAdmin">
					<div v-if="!isAdd">{{ mdl.userType|filterUserTypeName }}</div>
					<a-radio-group v-else v-decorator="['userType', { initialValue: '00' }]">
						<a-radio value="00">系统用户</a-radio>
					</a-radio-group>
				</a-form-item> -->
				<a-form-item label="账号">
					<a-input
						placeholder="请输入数字和字母组成的账号"
						v-decorator="[
							'username',
							{
								rules: [
									{ required: true, message: '请输入账号' },
									{ max: 50, message: '账号不超过50个字符' },
									{
										validator: validateUserName,
									},
								],
							},
						]"
						:disabled="!isAdd"
					/>
				</a-form-item>
				<a-form-item label="姓名">
					<a-input
						placeholder="请输入姓名"
						v-decorator="[
							'realName',
							{
								rules: [
									{ required: true, whitespace: true, message: '请输入姓名' },
									{ max: 50, message: '姓名不超过50个字符' },
								],
								getValueFromEvent: removeSpaces,
							},
						]"
					/>
				</a-form-item>
				<!-- <a-form-item label="手机号">
					<a-input placeholder="请输入手机号" v-decorator="[
							'phone',
							{
								rules: [
									{ required: true, message: '请输入手机号' },
									{
										validator: validatePhone
									}
								],
								trigger: 'blur'
							}
						]" />
				</a-form-item> -->
				<a-form-item extra="长度为6~30位，必须包含数字、字母、符号中至少一种" label="密码" v-if="isAdd">
					<a-input-password
						autocomplete="new-password"
						placeholder="请输入密码"
						v-decorator="[
							'password',
							{
								rules: [
									{ required: true, message: '请输入密码' },
									{ pattern: PwdReg, message: '长度为6~30位，必须包含数字、字母、符号中至少一种' },
								],
							},
						]"
					/>
				</a-form-item>
				<a-form-item v-if="isAdmin" label="所属卫健委">
					<a-select
						allowClear
						:disabled="!isAdd"
						v-decorator="['orgId', { rules: [{ required: true, message: '所属卫健委' }] }]"
						placeholder="所属卫健委"
						@change="changeOrg"
					>
						<a-select-option :value="item.orgId" v-for="(item, index) in orgList" :key="index">{{
							item.orgName
						}}</a-select-option>
					</a-select>
				</a-form-item>
				<a-form-item label="医院">
					<a-input
						placeholder="请选择医院"
						v-decorator="[
							'deptId',
							{
								rules: [{ required: isAdmin ? false : true, message: '请选择医院' }],
							},
						]"
						readOnly
						style="display: none"
					/>

					<span class="ant-input-group-wrapper">
						<span class="ant-input-wrapper ant-input-group">
							<input
								v-model="deptName"
								placeholder="请选择医院"
								type="text"
								readonly="true"
								class="ant-input"
							/>
							<span class="ant-input-group-addon"
								><a-icon @click="changeDept" slot="addonAfter" type="setting" style="cursor: pointer"
							/></span>
						</span>
					</span>
				</a-form-item>
				<a-form-item
					label="角色"
					v-show="roleList.length > 0 && (isAdd || (!isAdd && ['00', '02'].includes(mdl.userType)))"
				>
					<a-checkbox-group
						v-decorator="[
							'roleIds',
							{
								rules: [{ required: true, message: '请选择角色' }],
							},
						]"
					>
						<a-checkbox :value="item.roleId" v-for="(item, index) in roleList" :key="item.roleId">{{
							item.roleName
						}}</a-checkbox>
					</a-checkbox-group>
				</a-form-item>
				<a-form-item label="账号状态">
					<a-radio-group v-decorator="['status', { initialValue: '0' }]">
						<a-radio value="0">启用</a-radio>
						<a-radio value="1">停用</a-radio>
					</a-radio-group>
				</a-form-item>
				<a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="有效期">
					<j-date
						class="w100"
						v-decorator="['expiredDate']"
						placeholder="请选择有效期"
						date-format="YYYY-MM-DD"
					></j-date>
				</a-form-item>
			</a-form>
		</a-spin>
		<change-dept-modal ref="changeDeptModal" @selectDept="selectDept"></change-dept-modal>
		<avatar-modal ref="modal" @uploadImg="setavatar" />
	</globalModal>
</template>

<script>
import { sysManageapi } from '@/api/index.js';
import { ModalMixins } from '@/mixins';
import { PwdReg } from '@/utils/validate';
import { SEXTYPE, userTypeEnum, teacherRoleEnum } from '@/utils/enumeration';
import { mapState, mapActions } from 'vuex';
import changeDeptModal from '@/components/changeDeptModal.vue';
import AvatarModal from '@/components/AvatarModal';
import JDate from '@/components/JDate';
import md5 from 'md5';
export default {
	name: 'addOrEditUserModal',
	mixins: [ModalMixins],
	data() {
		return {
			teacherRoleEnum,
			PwdReg,
			orgName: '',
			orgId: '',
			roleList: [],
			deptName: '',
			userId: '',
			oldphone: '',
			fileUrl: process.env.VUE_APP_FILE_API,
			avatar: '',
			orgList: [],
			deptList: [], //所属部门列表
			//userType:'00',//机构用户
		};
	},
	components: {
		changeDeptModal,
		AvatarModal,
		JDate,
	},
	created() {},
	methods: {
		initInfo(record = {}) {
			this.mdl = Object.assign({}, record);
			console.log('书苏苏苏' + JSON.stringify(record));
			this.title = (this.isAdd ? '新增' : '编辑') + this.modalTitle;
			this.visible = true;
			//this.userType = this.mdl.userType || '00';
			//获取一些初始下拉数据
			this.getDefaultList && this.getDefaultList();
		},
		async getDefaultList() {
			this.deptName = this.mdl.deptName || '';
			//this.avatar = this.mdl.avatar;
			this.orgId = this.mdl.orgId;
			if (this.isAdmin && this.orgList.length == 0) {
				this.getAllOrgList();
			}
			this.roleList = [];
			if ((this.isAdmin && this.orgId) || !this.isAdmin) {
				await this.getRoleList();
			}
			this.$nextTick(() => {
				this.form.resetFields();
				this.setFieldsValue();
			});
			if (this.mdl.roleList && this.mdl.roleList.length > 0) {
				let roleIds = this.mdl.roleList.map((item) => item.roleId);
				this.$nextTick(() => {
					this.form.setFieldsValue({ roleIds: roleIds });
				});
			}
		},
		handleOk() {
			const _this = this;
			// 触发表单验证
			this.form.validateFields((err, values) => {
				// 验证表单没错误
				if (!err) {
					console.log('val', values);
					let parameter = Object.assign(
						{},
						values,
						this.mdl.userId
							? {
									userId: this.mdl.userId,
							  }
							: ''
					);
					if (_this.isAdd) {
						parameter.password = md5(parameter.password);
					}
					_this.confirmLoading = true;
					this.$postAction(_this.isAdd ? sysManageapi.userUrl.add : sysManageapi.userUrl.edit, parameter)
						.then((res) => {
							if (res && res.code == 1) {
								_this.$message.success('保存成功');
								_this.$emit('ok', _this.isAdd);
								_this.form.resetFields();
								_this.visible = false;
							}
						})
						.finally(() => {
							_this.confirmLoading = false;
						});
				}
			});
		},
		getRoleList() {
			return this.$postAction(sysManageapi.roleUrl.getAllList, {
				orgId: this.orgId || '',
			}).then((res) => {
				if (res && res.code == 1) {
					this.roleList = res.data.filter(
						(item) => item.roleCode != 'doctor' && item.roleCode != 'mang_admin'
					);
					//this.roleList = res.data;
					// let teacherRoleEnumCodes = teacherRoleEnum.map((item) => item.roleCode);
					// teacherRoleEnumCodes.push('parents_admin');
					// if (res.data && res.data.length > 0) {
					// 	for (let i = 0; i < res.data.length; i++) {
					// 		// if (!teacherRoleEnumCodes.includes(res.data[i].roleCode)) {
					// 		// 	this.roleList.push(res.data[i])
					// 		// }
					// 		//this.roleList.push(res.data[i]);
					// 	}
					// }
				}
			});
		},
		getAllOrgList() {
			this.$postAction(sysManageapi.orgUrl.getAllList).then((res) => {
				if (res && res.code == 1) {
					this.orgList = res.data;
				}
			});
		},
		changeDept(value) {
			if (this.isAdmin && !this.orgId) {
				this.$message.error('请先选择一个机构');
				return false;
			}
			this.$refs.changeDeptModal.show(this.orgId);
		},
		selectDept(dept) {
			this.deptName = dept.deptName;
			this.$nextTick(() => {
				this.form.setFieldsValue({
					deptId: dept.deptId,
				});
			});
		},
		validatePhone(rule, value, callback) {
			if (value) {
				if (this.oldphone == value) {
					callback();
				} else if (/^1[0-9]{10}$/.test(value)) {
					callback();
				} else {
					callback('请输入正确的手机号码');
				}
			} else {
				callback();
			}
		},
		validateUserName(rule, value, callback) {
			if (value) {
				if (!this.isAdd) {
					callback();
				} else if (/^[0-9a-zA-Z]+$/.test(value)) {
					callback();
				} else {
					callback('账号只能由数字、字母组成');
				}
			} else {
				callback();
			}
		},

		changeOrg(e) {
			this.orgId = e;
			this.deptList = [];
			this.deptName = '';
			this.form.setFieldsValue({
				deptId: undefined,
				roleIds: [],
			});
			this.roleList = [];
			if (this.orgId) {
				this.getRoleList();
			}
		},
		setavatar(pic, previewUrl) {
			this.avatar = previewUrl;
			this.form.setFieldsValue({
				avatar: pic,
			});
		},
	},
	filters: {
		filterUserTypeName: function (value) {
			if (userTypeEnum && userTypeEnum.length > 0) {
				return userTypeEnum.find((item) => item.value == value).text || '';
			} else {
				return '';
			}
		},
	},
};
</script>

<style scoped lang="less">
.avatar-uploader-row {
	display: flex;
	align-items: center;
}

.avatar-uploader {
	width: 100px;
	height: 100px;
	text-align: center;
	border: 1px solid #ccc;
	border-radius: 100%;
	line-height: 1;
	cursor: pointer;
	overflow: hidden;

	i {
		font-size: 32px;
		color: #999;
	}

	.ant-upload-text {
		margin-top: 8px;
		color: #999;
	}

	img {
		width: 100%;
		height: 100%;
	}
}

/deep/ .ant-checkbox-group {
	margin: 0 -4px;
}

/deep/ .ant-checkbox-wrapper {
	margin: 0 4px;
}

.ant-upload-preview {
	position: relative;
	width: 100%;
	max-width: 120px;
	height: 120px;
	border-radius: 8px;
	overflow: hidden;

	.mask {
		opacity: 0;
		position: absolute;
		background: rgba(0, 0, 0, 0.3);
		cursor: pointer;
		transition: opacity 0.4s;

		&.active {
			opacity: 1 !important;
		}

		&:hover {
			opacity: 1;
		}

		i {
			font-size: 2rem;
			position: absolute;
			top: 50%;
			left: 50%;
			margin-left: -1rem;
			margin-top: -1rem;
			color: #d6d6d6;
		}
	}

	img,
	.mask {
		width: 100%;
		max-width: 180px;
		height: 100%;
		overflow: hidden;
	}

	.upload-img {
		font-size: 80px;
		text-align: center;
	}
}
</style>
